package com.example.algorithm.backtrcaking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author : zhy
 * @since : 2022/8/13
 * 组合总和
 */
public class CombinationSum {

    /**
     * 某个元素可以多次使用
     * @param candidates
     * @param target
     * @return
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<Integer> list = new ArrayList<>();
        List<List<Integer>> listList = new ArrayList<>();
        Arrays.sort(candidates);
        int len=candidates.length;
        backTrack(list,listList,len,candidates,target,0,0);
        return listList;
    }

    private void backTrack(List<Integer> list, List<List<Integer>> listList, int len, int[] candidates, int target,int sum,int index) {

        if(sum==target){
            listList.add(new ArrayList<>(list));
            return;
        }
        if(sum>target){
            return;
        }

        for(int i=index;i<len;i++)
        {
            if(sum+candidates[i]>target){
                break;
            }
            list.add(candidates[i]);
            sum+=candidates[i];
            backTrack(list, listList, len, candidates, target, sum,i);
            int num=list.get(list.size()-1);
            sum-=num;
            list.remove(list.size()-1);
        }
    }


    public static void main(String[] args) {
        CombinationSum combinationSum = new CombinationSum();
        int []can={2,3,6,7};
        List<List<Integer>> listList = combinationSum.combinationSum(can, 7);
        listList.stream().forEach(System.out::println);
    }
}
